package com.yimi.yinhepda.views.offline.unload;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.OfflineUnLoadTaskCacheAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.OfflineTaskEntity;
import com.yimi.yinhepda.entity.bean.PdaReceiveVo;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.FastClick;
import com.yimi.yinhepda.utils.ListUtils;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.views.load_module.ScanSealSignActivity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 离线卸车暂存界面
 *
 * @author 000432
 */
public class OffLineUnLoadCacheActivity extends BaseActivity implements CommonViewHolder.onItemCommonClickListener {

    private RecyclerView listView;
    private OfflineUnLoadTaskCacheAdapter adapter;
    private TextView num;

    private UnloadTaskTableDao mUnloadTaskTableDao;
    private UnloadScanTableDao mUnloadScanTableDao;
    private List<OfflineTaskEntity> listTaskEntity;
    private OfflineTaskEntity offlineTaskEntity;
    private String userCode;
    private int operTypeCode = 4;
    public static Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_unload_cache);
    }

    @SuppressLint("HandlerLeak")
    @Override
    protected void onStart() {
        super.onStart();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                showToast("数据上传成功");
                initData();
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();

        initView();
        initData();
        //上传数据
        upLoadSubmit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler = null;
    }

    @Override
    public String getPageName() {
        return "离线卸车暂存";
    }

    public void initView() {
        ((TextView) findViewById(R.id.title)).setText("离线卸车暂存");
        num = findViewById(R.id.num);
        listView = findViewById(R.id.unload_task_cash_listview);
        findViewById(R.id.unload_task_cash_btn_back).setOnClickListener(this);
        findViewById(R.id.unload_task_cash_btn_del).setOnClickListener(this);
        findViewById(R.id.unload_task_cash_btn_exec).setOnClickListener(this);
        findViewById(R.id.btn_upload).setOnClickListener(this);
    }

    private void initData() {
        userCode = sharedPreferUtil.getValue(Common.USER_CODE);
        mUnloadTaskTableDao = new UnloadTaskTableDao();
        mUnloadScanTableDao = new UnloadScanTableDao();
        listTaskEntity = new ArrayList<>();

        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode, userCode) + "");
        //获取离线卸车数据
        listTaskEntity = OffLineUnLoadUtil.offlineUnloadData(userCode,sharedPreferUtil.getDeptCode());
        listTaskEntity = sortList(listTaskEntity);
        adapter = new OfflineUnLoadTaskCacheAdapter(this, listTaskEntity, this);
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        listView.setAdapter(adapter);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        //防抖
        if (FastClick.isFastClick()) {
            return;
        }

        switch (v.getId()) {
            case R.id.unload_task_cash_btn_back:
                finish();
                break;
            case R.id.unload_task_cash_btn_del:
                //删除按钮
                if (offlineTaskEntity == null || !offlineTaskEntity.isCheck()) {
                    showToast("请选择一项删除！");
                    return;
                }
                String offlineTaskNo = offlineTaskEntity.getOfflineTaskNo();
                deleteData(offlineTaskNo);
                break;
            case R.id.unload_task_cash_btn_exec:
                //执行按钮
                if (offlineTaskEntity == null || !offlineTaskEntity.isCheck()) {
                    showToast("请先选中要执行的项！");
                    return;
                }

                if (offlineTaskEntity.getLoadType() == 3) {
                    //已发车状态不可继续执行，给出提示
                    MyDialog.showAlertDialog(this, "系统提示",
                            "当前选择的执行数据已经卸车完成，不能再次执行", "是");
                    return;
                }
                //装车状态，1-发车，2-未发车，3-卸车，4-未卸车，5-已解封，6-单独封车
                if (offlineTaskEntity.getLoadType() != 5 && offlineTaskEntity.getLoadType() != 3) {
                    //解封车
                    Intent intent = new Intent(this, ScanSealSignActivity.class);
                    //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
                    intent.putExtra("loadType", 2);
                    intent.putExtra("offlineTaskNo", offlineTaskEntity.getOfflineTaskNo());
                    intent.putExtra("carPlateNo", offlineTaskEntity.getCarNo());
                    intent.putExtra("lineType", offlineTaskEntity.getLineType() + "");
                    startActivity(intent);
                } else {
                    Intent unloadScanIntent = new Intent(OffLineUnLoadCacheActivity.this, OffLineUnloadActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("offlineTaskNo", offlineTaskEntity.getOfflineTaskNo());
                    unloadScanIntent.putExtras(bundle);
                    startActivity(unloadScanIntent);
                }
                finish();
                break;
            case R.id.btn_upload:
                //数据上传
                upLoadSubmit();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClickListener(int position) {
        offlineTaskEntity = listTaskEntity.get(position);
        for (OfflineTaskEntity entity : listTaskEntity) {
            entity.setCheck(false);
        }
        offlineTaskEntity.setCheck(true);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    /**
     * 提交装车数据
     */
    private void upLoadSubmit() {
        if (listTaskEntity == null || listTaskEntity.isEmpty()) {
            showToast("无数据上传！");
            return;
        }
        //组装数据上传
        final PdaReceiveVo pdaReceiveVo = OffLineUnLoadUtil.submitData(listTaskEntity, userCode, operTypeCode);
        if (pdaReceiveVo.getTaskEntityList().isEmpty()) {
            showToast("没有已卸车数据上传！");
            return;
        }

        showPgDlg("数据上传中...");
        OffLineUnLoadUtil.requestNet(pdaReceiveVo, userCode, operTypeCode, new UICallBack() {
            @Override
            public void onError(String msg) {
                dismissPgDlg();
                showToast(msg);
                SoundVibratorManager.playSound(2);
                initData();
            }

            @Override
            public void onSuccess(Object obj) {
                dismissPgDlg();
                showToast("数据上传成功");
                SoundVibratorManager.playSound(1);
                initData();
            }
        });
    }

    /**
     * 根据离线任务号删除数据
     *
     * @param offlineTaskNo 离线任务号
     */
    private void deleteData(final String offlineTaskNo) {
        try {
            //删除任务表和扫描表
            List<UnloadTaskTable> list = mUnloadTaskTableDao.findStowage(offlineTaskNo, userCode);
            mUnloadTaskTableDao.delete(list);
            Iterator<OfflineTaskEntity> it = listTaskEntity.iterator();
            while (it.hasNext()) {
                OfflineTaskEntity taskEntity = it.next();
                if (taskEntity.getOfflineTaskNo().equals(offlineTaskNo)) {
                    it.remove();
                }
            }

            final ScanDetailVoDao scanDetailVoDao = new ScanDetailVoDao();
            final List<UnloadScanTable> unloadScan = mUnloadScanTableDao.getDataByStowageAndType(offlineTaskNo, operTypeCode, userCode);
            //设置未上传数
            num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode, userCode) - unloadScan.size() + "");

            //noinspection AlibabaAvoidManuallyCreateThread
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //扫描列表数据
                        scanDetailVoDao.delete(scanDetailVoDao.getDataByStowageAndType(offlineTaskNo, operTypeCode, userCode));
                        //扫描运单数据
                        mUnloadScanTableDao.delete(unloadScan);
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                    }
                }
            }).start();
        } catch (Exception e) {
            LogUtil.e(e.toString());
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 数据排序
     * 一级排序 白>绿,isUpload
     */
    private List<OfflineTaskEntity> sortList(List<OfflineTaskEntity> list) {
        String[] sortNameArr = {"isUpload"};
        // true升序,false降序
        boolean[] isAscArr = {true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }
}
